/*
 * @Author: rogi
 * @Date: 2022-08-18 14:58:18
 * @LastEditTime: 2022-08-18 17:21:54
 * @LastEditors: rogi
 * @Description: 描述
 */
import fs from 'fs'
import os from 'os'
import dayjs from 'dayjs'

const args = process.argv.slice(2);
const BuildEnd = args[0].split('BuildEnd')
const env = BuildEnd[0];
fs.readFile(`./.env.${env}`,'utf8', (err, data) => {
  if (err) {
    throw err;
  }
  if (args[0].indexOf('BuildEnd') !== -1) {
    data += `打包结束时间：${dayjs().format('YYYY-MM-DD HH:mm:ss')};状态正常;`
  } else {
    data.split(/\r\n/g).forEach(el => {
      const item = el.split(' = ')
      if (item && item.length >= 1 && item[0] === 'VITE_V') {
        const v = item[1]
        let vSplit = v.split('.')
        vSplit[vSplit.length - 1] = vSplit[vSplit.length - 1] * 1 + 1
        vSplit = vSplit.join('.')
        data = data.replace(new RegExp(v), vSplit)
      }
    })
    function getIpAddress() {
      var interfaces = os.networkInterfaces();
      for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
          var alias = iface[i];
          if (
            alias.family === "IPv4" &&
            alias.address !== "127.0.0.1" &&
            !alias.internal
          ) {
            return alias.address;
          }
        }
      }
    }
    const myHost = getIpAddress();
    data += `\r\n打包开始时间：${dayjs().format('YYYY-MM-DD HH:mm:ss')}，打包人：${myHost}  ---  `
  }
  fs.writeFile(`./.env.${env}`,data,'utf8', () => {});
});